from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models import User
from app.schemas import UserSchema
from app import db

bp = Blueprint('profile', __name__, url_prefix='')

@bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取当前用户的个人信息"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get_or_404(current_user_id)
        
        return jsonify({
            'status': 'success',
            'data': UserSchema().dump(user)
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@bp.route('/profile', methods=['PUT'])
@jwt_required()
def update_profile():
    """更新当前用户的个人信息"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get_or_404(current_user_id)
        data = request.get_json()

        if 'email' in data:
            user.email = data['email']
        
        # 如果需要更新密码
        if 'old_password' in data and 'new_password' in data:
            if not user.check_password(data['old_password']):
                return jsonify({
                    'status': 'error',
                    'message': 'Invalid old password'
                }), 400
            user.set_password(data['new_password'])

        db.session.commit()

        return jsonify({
            'status': 'success',
            'message': 'Profile updated successfully',
            'data': UserSchema().dump(user)
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 